/*
 * $Id: JsonRpcRequestFactory.java 50372 2007-03-28 18:00:51Z jdamick $
 *
 * Copyright 2006- Revolution Health Group.  All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Revolution Health Group.  (Confidential Information).
 * You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license 
 * agreement you entered into with Revolution Health Group.
 *
 */
package org.javason.jsonrpc;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.javason.json.BeanToJsonSerializer;

public class JsonRpcRequestFactory {
	private JsonRpcRequestFactory() {}
	
	public static JSONObject createJsonRpcRequest(Object id, 
			String methodName, JSONArray params) {
		
		JSONObject requestObj = initializeRequestObject(id, methodName);
		
		try {
			requestObj.put(JsonRpcConstants.PARAMS, params);
		} catch (JSONException e) {
			throw new IllegalArgumentException(e);
		}
		return requestObj;
	}
	
	public static JSONObject createJsonRpcRequest(String methodName, Object ... params) {
		JSONArray paramArray = new JSONArray();
		for (Object param : params) {
			paramArray.add(BeanToJsonSerializer.serialize(param));
		}
		return createJsonRpcRequest(0, methodName, paramArray);
	}
	
	
	public static JSONObject createJsonRpcRequest(Object id, 
			String methodName, JSONObject params) {
		
		JSONObject requestObj = initializeRequestObject(id, methodName);
		
		try {
			requestObj.put(JsonRpcConstants.PARAMS, params);
		} catch (JSONException e) {
			throw new IllegalArgumentException(e);
		}
		return requestObj;
	}
	
	private static JSONObject initializeRequestObject(Object id, String methodName) {
		JSONObject requestObj = new JSONObject();
		try {
			requestObj.put(JsonRpcConstants.ID, id);
			requestObj.put(JsonRpcConstants.METHOD, methodName);
			requestObj.put(JsonRpcConstants.VERSION, JsonRpcConstants.VERSION_VALUE);
			
		} catch (JSONException e) {
			throw new IllegalArgumentException(e);
		}
		return requestObj;
	}
}
